package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.DateFormatter;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WorkspaceService workspaceService;
    /**
     * 根据时间区间统计营业额
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        if (end.isBefore(begin)) {
            throw new IllegalArgumentException("结束日期不能早于开始日期");
        }
        //查询出这个时间区间当天的营业额（黑马哪里是一个个查，这里直接一下子查完吧）
            //设置查询条件:设置日期范围，同时订单需要已完成
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("status", Orders.COMPLETED);
        paramMap.put("begin", LocalDateTime.of(begin, LocalTime.MIN));//设置为一天中的开始
        paramMap.put("end",LocalDateTime.of(end,LocalTime.MAX));
        Map<String, Map<String, Object>> stringMapMap = orderMapper.sumTurnoverByDate(paramMap);

        //这里像找找有没有什么好方法的，感觉封装成对会好点
            //TODO 想封装成价值对，但是找了半天没有特别好的方法
        //获取整个的时间区间(每想到啥好方法，只能一个个算了)
            //这里想用双指针算法的，但是实现起来真的太过麻烦了，需要各种判断，太麻烦了，放弃了
        List<LocalDate> dateList=new ArrayList<>();
        List<BigDecimal> turnoverList=new ArrayList<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for(; !end.isBefore(begin); begin=begin.plusDays(1)){
            //!(end<begin)
            dateList.add(begin);
            Map<String, Object> map = stringMapMap.get(dateTimeFormatter.format(begin));
            if (map!=null){
                BigDecimal turnover=(BigDecimal) map.get("turnover");
                turnoverList.add(turnover);
            }else{
                turnoverList.add(BigDecimal.ZERO);
            }
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))//将数组变成字符串用","合并
                .turnoverList(StringUtils.join(turnoverList,",")).build();
    }

    /**
     * 根据时间区间统计用户数量
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        List<Integer> newUserList=new ArrayList<>();
        List<Integer> totalUserList=new ArrayList<>();
        //查看每天的情况
        for(;!begin.isAfter(end);begin=begin.plusDays(1)){//begin <= end  !(begin > end)
            LocalDateTime beginTime=LocalDateTime.of(begin,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
            Map map=new HashMap<>();
            map.put("end",endTime);
            //总用户数量 select count(id) from user where  create_time < ?
            Integer totalUser=userMapper.countByMap(map);
            //新增用户数量 select count(id) from user where create_time > ? and create_time < ?
            map.put("begin",beginTime);
            Integer newUser= userMapper.countByMap(map);
            dateList.add(begin);
            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,",")).build();
    }

    /**
     * 根据时间区间统计订单数量
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        List<Integer> orderCountList=new ArrayList<>();
        List<Integer> validOrderCountList=new ArrayList<>();
        //查询每天的情况
            //begin<=end  !(begin>end)
        for(;!begin.isAfter(end);begin=begin.plusDays(1)){
            LocalDateTime beginTime=LocalDateTime.of(begin,LocalTime.MIN);
            LocalDateTime endTime=LocalDateTime.of(begin,LocalTime.MAX);
            //查询每天的总订单数 select count(id) from orders where order_time > ? and order_time < ?
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //查询每天的有效订单数 select count(id) from orders where order_time > ? and order_time < ? and status = ?
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            dateList.add(begin);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        //这里其实在循环中整更合适，这里主要是复习下stream
        //时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
                //reduce是组合成一块，参数是二元操作（对两个元素的操作）
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){//主要怕除0
            orderCompletionRate=totalOrderCount.doubleValue()/totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate).build();
    }

    /**
     * 根据时间区间统计指定状态的订单数量
     * （主要是为了复用）
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime beginTime,LocalDateTime endTime,Integer status){
        Map map=new HashMap();
        map.put("status",status);
        map.put("begin",beginTime);
        map.put("end",endTime);
        return orderMapper.countByMap(map);
    }

    /**
     * 查询指定时间区间内的销量排名top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList=orderMapper.getSalesTop10(beginTime,endTime);
        //转换成数组字符串  跟StringUtils.join一样
        String nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.joining(","));
        String numberList = goodsSalesDTOList.stream().map(i -> i.getNumber().toString()).collect(Collectors.joining(","));
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList).build();
    }

    /**
     * 导出近30天的运营数据报表
     * (不算今天)
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //获取静态文件中的模板文件，同时将他变成流
        //通过输出流的形式读取指定的excel文件(读到了内存中)
        //已经获取到浏览器传输对应的流
        try(InputStream in=this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
            XSSFWorkbook excel=new XSSFWorkbook(in);
            ServletOutputStream out = response.getOutputStream();){//try-with-resource:方便后续自动关闭
            //获取到需要填入的sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            LocalDate now = LocalDate.now();
            LocalDate begin=now.minusDays(30);
            LocalDate end=now.minusDays(1);

            //填充下时间信息
            sheet.getRow(1).createCell(1).setCellValue(begin+"至"+end);

            //查询概览运营数据，并填入到对应的位置中
            BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
            XSSFRow row = sheet.getRow(3);
            row.createCell(2).setCellValue(businessData.getTurnover());
            row.createCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.createCell(6).setCellValue(businessData.getNewUsers());
            row=sheet.getRow(4);
            row.createCell(2).setCellValue(businessData.getValidOrderCount());
            row.createCell(4).setCellValue(businessData.getUnitPrice());

            //查询每天的明细数据，同时填入
            for(int i=0;i<30;++i){
                LocalDate date=begin.plusDays(i);
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row=sheet.getRow(i+7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流的形式，将文件下载到客户端
            excel.write(out);
//            //关闭资源(自动进行)
//            out.flush();
//            out.close();
//            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
